<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 信息提示框 -->
        <el-alert
          title="添加商品信息"
          type="info"
          center
          show-icon
          :closable="false">
        </el-alert>

        <!-- 步骤条 -->
        <el-steps :space="200" :active="Stepsactive - 0" finish-status="success" align-center>
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>

        <!-- 标签页 -->
        <el-form ref="addGoodFormRef" :model="addGoodForm" :rules="addGoodFormRules" label-width="80px" label-position="top">
          <el-tabs v-model="Stepsactive" :tab-position="'left'" :before-leave="beforeLeave">
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addGoodForm.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input v-model="addGoodForm.goods_price"></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input v-model="addGoodForm.goods_weight"></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input v-model="addGoodForm.goods_number"></el-input>
              </el-form-item>
              <el-form-item label="商品分类">
                  <el-cascader
                     v-model="selectKeys"
                     :options="CateList"
                     :props="PropsConfigObj"
                     @change="handleChange">
                     </el-cascader>
                 </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name="1">
               <!-- 动态参数 -->
               <el-form-item v-for="item in ManyParamData" :key="item.attr_id" :label="item.attr_name">
                 <el-checkbox-group v-model="item.attr_vals" @change="checkBoxChange()">
                   <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border></el-checkbox>
                </el-checkbox-group>
               </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name="2">
              <!-- 静态属性 -->
              <el-form-item v-for="item in OnlyParamData" :key="item.attr_id" :label="item.attr_name">
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
              <!-- 上传图片 -->
                <el-upload
                  class="upload-demo"
                  :action="uploadRoad"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="uploadSuccess"
                  list-type="picture"
                  :headers="headerObj">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
              <!-- 富文本编辑器组件 -->
              <quill-editor v-model="addGoodForm.goods_introduce">
              </quill-editor>
              <el-Button class="btnAdd" type="primary" @click="add()">添加商品</el-Button>
            </el-tab-pane>
          </el-tabs>
        </el-form>
    </el-card>

    <!-- 打开缩略图对话框 -->
    <el-dialog
      title="展开图片"
      :visible.sync="setImgVisible"
      width="20%">
      <img :src="ImgRoad" alt="">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {

  data() {
    return {
      // 步骤条显示步骤
      Stepsactive: '0',
      //  添加商品表单数据对象
      addGoodForm: {
        goods_name: '',
        // 商品分类
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        // 动态/静态参数
        // attrs: [
        //   {}
        // ],
        // 图片
        pics: [],
        // 商品的详情描述
        goods_introduce: '',
        attrs: []
      },
      //  商品分类的所有数据
      CateList: [],
      //  商品分类级联选择器选中的分类
      selectKeys: [],
      // 级联选择器配置对象
      PropsConfigObj: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      //  添加商品表单数据对象验证规则
      addGoodFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ]
      },
      // 动态参数数据
      ManyParamData: [],
      // 静态参数数据
      OnlyParamData: [],
      // 上传图片路径
      uploadRoad: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传组件的请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 展开图的显示与否
      setImgVisible: false,
      // 展开图片路径
      ImgRoad: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    getCateList() {
      this.$http.get('categories').then(res => {
        console.log(res.data)
        if (res.data.meta.status !== 200) return this.$message.error('获取商品列表失败')
        this.CateList = res.data.data
      })
    },
    // 当级联选择器发生改变时
    handleChange() {
      this.addGoodForm.goods_cat = this.selectKeys
      console.log(this.addGoodForm.goods_cat)
    },
    // 点击标签检测是否选中分类
    beforeLeave(activeName, oldActiveName) {
      if (this.selectKeys.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }

      if (activeName === '1') {
        this.getParamsDataList('many')
      } else if (activeName === '2') {
        this.getParamsDataList('only')
      }
    },
    // 获取动静态属性
    getParamsDataList(ParamsType) {
      // 根据ID查参数
      this.$http.get(`categories/${this.selectKeys[2]}/attributes`, {
        params: {
          sel: ParamsType
        }
      }).then(res => {
        if (res.data.meta.status !== 200) return this.$message.error('获取参数失败')
        if (ParamsType === 'many') {
          res.data.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          })
          this.ManyParamData = res.data.data
          return
        }
        this.OnlyParamData = res.data.data
      })
    },
    // 复选框发生改变
    checkBoxChange() {
      console.log(this.ParamsList)
    },
    // 点击打开缩略图
    handlePreview(file) {
      this.setImgVisible = true
      this.ImgRoad = file.response.data.url
    },
    // 删除缩略图
    handleRemove(file) {
      console.log(file)
      let index = ''
      index = this.addGoodForm.pics.findIndex(item => {
        return item.pic === file.response.data.tmp_path
      })
      this.addGoodForm.pics.splice(index, 1)
      console.log(this.addGoodForm)
    },
    // 图片上传成功
    uploadSuccess(response) {
      // 将上传成功的图片的临时路径添加到pic里面
      console.log(response)
      this.addGoodForm.pics.push({ pic: response.data.tmp_path })
    },
    // 添加商品
    add() {
      // 预验证
      this.$refs.addGoodFormRef.validate(valid => {
        if (!valid) return
        // 执行业务逻辑
        let form = ''
        form = _.cloneDeep(this.addGoodForm)
        form.goods_cat = form.goods_cat.join(',')

        // 添加动态参数
        this.ManyParamData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join(',') }
          form.attrs.push(newInfo)
        })
        // 添加静态属性
        this.OnlyParamData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          form.attrs.push(newInfo)
        })
        // 添加商品
        this.$http.post('goods', form).then(res => {
          console.log(res.data)
          if (res.data.meta.status !== 201) return this.$message.error('添加商品失败')
          this.$message.success('添加商品成功')
          // 重定向路由
          this.$router.push('/goods')
        })
        console.log(form)
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .el-steps {
    margin: 10px 0 10px 0;
  }
  .el-input {
    width: 95%;
  }
  .el-checkbox {
    margin: 0 0 10px 10px !important;
  }
  .btnAdd {
    margin-top: 10px;
  }
</style>
